/*
 * @(#)CheckAndCreateSynTable.java   1.0  2021年11月17日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.dts.offline.exec;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.swift.dao.db.datasource.HandlerDataSource;
import com.swift.dao.db.springjdbc.Jdbc;
import com.swift.dts.dao.model.SynObjectKey;
import com.swift.dts.util.CreateExecSql;
import com.swift.util.type.TypeUtil;

/**
 * 初始化表
 * 
 * @author zhengjiajin
 * @version 1.0 2021年11月17日
 */
@Component
public class CheckAndCreateSynTable {
    private static final Logger log = LoggerFactory.getLogger(CheckAndCreateSynTable.class);
    @Autowired
    private Jdbc jdbc;

    public void checkAndCreateTable(SynObjectKey key) {
        try {
            String showCreate = "SHOW CREATE TABLE " + key.getDbName() + "." + key.getTableName();
            HandlerDataSource.putDataSource(key.getDataSource());
            Map<String, Object> tableMap = jdbc.queryForMap(showCreate);
            if (TypeUtil.isNull(tableMap)) return;
            String createSql = TypeUtil.toString(tableMap.get("Create Table"));
            if (TypeUtil.isNull(createSql)) return;
            createSql = createSql.substring(createSql.indexOf("("));
            createSql = "CREATE TABLE "+CreateExecSql.dbTable(key.getDbName(), key.getTableName())+" "+createSql;
            HandlerDataSource.putDataSource(key.getDestination());
            jdbc.execute(createSql);
        } catch (Exception ex) {
            log.error("读取表结构异常",ex);
        } finally {
            HandlerDataSource.clear();
        }
    }
}
